package leetcode;

/**
 * 合并两个有序链表
 * @author ：徐梦轲
 * @date ：2022/5/22 0022 21:03
 */
class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

public class Solution {
    //方法1：迭代
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode node = new ListNode(0);
        ListNode cur1 = list1;
        ListNode cur2 = list2;
        ListNode head = node;
        while (cur1 != null && cur2 != null) {
            if (cur1.val < cur2.val) {
                head.next = cur1;
                head = cur1;
                cur1 = cur1.next;
            } else {
                head.next = cur2;
                head = cur2;
                cur2 = cur2.next;
            }
        }
        if (cur1 != null) {
            head.next = cur1;
        }
        if (cur2 != null) {
            head.next = cur2;
        }
        return node.next;
    }

    //解法2：递归
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        } else if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }

    }
}
